package com.jxm.channel;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: jxm
 * @Description: 读取数据
 * @Date: 2024-2-7 14:07
 * @Version: 1.0
 */
public class FileChannelDemo1 {

    //FileChannel读取数据到buffer中
    public static void main(String[] args) throws Exception {
        //创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile("F:\\file\\01.txt", "rw");
        FileChannel channel = aFile.getChannel();
        //创建Buffer
        ByteBuffer buf = ByteBuffer.allocate(10);
        //读取数据到buffer中
        int bytesRead = channel.read(buf);
        while (bytesRead != -1) {
            System.out.println("读取： " + bytesRead);
            buf.flip();//反转读写模式
            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            buf.clear();
            bytesRead = channel.read(buf);
        }
        aFile.close();
        System.out.println("\n操作结束");
    }
}
